﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft.Web
{
    /// <summary>
    /// 权限映射
    /// </summary>
    public class PermissionMap
    {
        private readonly IDictionary<string, PermissionInfo> data;
        public PermissionMap(IDictionary<string, PermissionInfo> datamap)
        {
            this.data = datamap;
        }

        public IDictionary<string, PermissionInfo> Data { get { return data; } }

        /// <summary>
        /// 根据指定的权限数据获取当前权限映射表的数据列
        /// </summary>
        /// <param name="permissions">Key为权限名称，Value为是否有权限</param>
        /// <returns></returns>
        public bool[] GetPermissionData(Dictionary<string, bool> permissions)
        {
            IDictionary<string, bool> pers = new Dictionary<string, bool>();
            foreach (var item in this.data)
            {
                pers.Add(item.Key, false);
            }
            if (permissions != null)
            {
                foreach (var item in permissions)
                {
                    if (item.Value && pers.ContainsKey(item.Key))
                    {
                        pers[item.Key] = true;
                    }
                }
            }
            List<bool> bols = new List<bool>();
            foreach (var item in pers.Values)
            {
                bols.Add(item);
            }
            return bols.ToArray();
        }

        /// <summary>
        /// 将权限数据转为base64字符串
        /// </summary>
        /// <param name="permissionData"></param>
        /// <returns></returns>
        public string PermissionsDataToBase64(bool[] permissionData)
        {
            BitArray ba = new BitArray(permissionData);
            var bytes = ba.ToByteArray();
            return Convert.ToBase64String(bytes);
        }
        /// <summary>
        /// 获取是否具有权限
        /// </summary>
        /// <param name="permissionData"></param>
        /// <param name="permissionName"></param>
        /// <returns></returns>
        public bool GetPermissionEnabled(string permissionData, string permissionName)
        {
            var bytes = Convert.FromBase64String(permissionData);
            var bitArray = new BitArray(bytes);
            var i = this.data.Keys.IndexOf(permissionName);
            if (i == -1)
            {
                throw new Exception($"未定义权限【{permissionName}】");
            }
            if (i >= bitArray.Length)
            {
                throw new Exception($"权限数据不完整，请清除缓存并重新登录。");
            }
            return bitArray[i];
        }
    }


    public class PermissionInfo
    {
        public string[] Path { get; set; }

        public string Remark { get; set; }
    }
}
